package com.itheima.factory;

import com.itheima.service.AdminService;
import com.itheima.service.impl.AdminServiceImpl;
import com.itheima.utils.TransactionManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;


public class BeanFactory {

    @Autowired
    @Qualifier("adminService")
    private AdminServiceImpl adminService ;


    @Autowired
    @Qualifier("transactionManager")
    private TransactionManager transactionManager;



    /**
     * 获取代理对象
     * @return
     */
    public AdminServiceImpl getAdminService() {

        return (AdminServiceImpl) Proxy.newProxyInstance(
                adminService.getClass().getClassLoader(),
                adminService.getClass().getInterfaces(),
                new InvocationHandler() {
                    /**
                     * 添加事物的支出
                     * @param o
                     * @param method
                     * @param objects
                     * @return
                     * @throws Throwable
                     */
                    @Override
                    public Object invoke(Object o, Method method, Object[] objects) throws Throwable {
                        Object result = null;
                        try {
                            transactionManager.start();
                            result = method.invoke(adminService, objects);
                            transactionManager.commit();
                        } catch (Exception e) {
                            transactionManager.rollback();
                            e.printStackTrace();
                        } finally {
                            transactionManager.release();
                        }
                        return result;
                    }
                }
        );
    }
}
